package com.hxzy.service.impl;

import com.hxzy.common.enums.AckCode;
import com.hxzy.common.exception.ServiceException;
import com.hxzy.common.exception.ServiceStringException;
import com.hxzy.config.security.AdminLoginResp;
import com.hxzy.entity.SysUser;
import com.hxzy.service.SpringSecurityUserDetailService;
import com.hxzy.service.SysMenuService;
import com.hxzy.service.SysRoleService;
import com.hxzy.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * @Author wy
 * @Description security登录认证权限接口实现
 * @Date 2023/9/26 10:31
 * @Version 1.0
 */
@Service
public class SpringSecurityUserDetailServiceImpl implements SpringSecurityUserDetailService {

    @Autowired
    private SysUserService  sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysMenuService sysMenuService;


    /**
     * spring security认证重写接口
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1、根据账号查询信息
        SysUser sysUserDB=this.sysUserService.findByUserName(username);
        if(Objects.isNull(sysUserDB)){
            throw new ServiceException(AckCode.USERNAME_PASSWORD_ERROR);
        }

        //2、判断账户是否锁定
        if(sysUserDB.getStatus().equals("1")){
            throw new ServiceException(AckCode.DEVICE_BANNED);
        }

        //3、账户被删除了
        if(sysUserDB.getDelFlag().equals("2")){
            throw new ServiceStringException("账户已被删除，不允许登录");
        }

        //4、查询账户拥有的角色有哪些
        Set<String> roleSet=this.sysRoleService.ownerRole(sysUserDB.getUserId());

        //5、菜单自己做判断
        //超级 管理员，拥有所有的菜单权限  car:store:page
        Set<String> menuSet=new HashSet<>();
        if(roleSet.contains("admin")){
            menuSet.add("*:*:*");
        }else{
            menuSet=this.sysMenuService.ownerMenuByUserId(sysUserDB.getUserId());
        }


        AdminLoginResp  adminLoginResp=new AdminLoginResp();
        adminLoginResp.setSysUser(sysUserDB);
        adminLoginResp.setMenuPermission(menuSet);
        adminLoginResp.setRolePermissions(roleSet);

        return adminLoginResp;
    }
}
